package com.example.feigntest.customconfig.decoder;

import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;

import com.example.feigntest.dto.Fruit;
import com.example.feigntest.feignclient.DecoderTestClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 描述：Feign 编码器,负责将 http response 转成 feign 接口定义的返回值类型
 *
 * @author YangQun by 2020/10/17
 */
public class CustomFeignDecoder implements Decoder {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private static final Charset UTF_8 = StandardCharsets.UTF_8;

    /**
     * @param response response
     * @param type 以 {@link DecoderTestClient#test()} 为例,这个 type 就是返回值 {@link Fruit} 的类型
     */
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        try(InputStream inputStream = response.body().asInputStream()) {
            byte[] bodyBytes = inputStream.readAllBytes();

            /*
             * 我这里非常清楚的知道 {@link DecoderTestClient} 中请求的所有方法(也就是{@link FeignDecoderTestController}) ,
             * 返回的都是以 ":" 作分隔符的字符串
             */
            String[] bodyStrArr = new String(bodyBytes, UTF_8).split(":");

            System.err.println("-------------------------------------------------");
            log.info("CustomFeignDecoder type = {}", type);


            /*
             * 同上,我这里知道 {@link DecoderTestClient} 接口定义返回的都是 {@link Fruit} 类型
             * 正常流程应该判断下 type 参数的类型在作转换
             */
            Fruit fruit = new Fruit();
            fruit.setName(bodyStrArr[0]);
            fruit.setPrice(Integer.parseInt(bodyStrArr[1]));
            return fruit;
        }
    }
}
